package search;


/**
 * 二分查找 可使用递归与非递归 只能返回一个索引
 * 前提：有序
 */
public class BinarySearch {
    private static int counts = 0;
    public static void main(String[] args) {
        int[] arr = {0,1,2,3,4,5,6,7,8,9};
        int index = binarySearch(arr,0,arr.length-1,8);
        System.out.println(index);
        System.out.println("执行了"+counts+"次");
    }
    private static int binarySearch(int[]arr,int left,int right,int value){
        counts++;
        int mid = left + (right-left) / 2;
        while(left<=right){
            if (arr[mid]>value){
                return binarySearch(arr,left,mid-1,value);
            }else if(arr[mid]<value){
                return binarySearch(arr,mid+1,right,value);
            }else {
                return mid+1;
            }
        }
        // left > right 未找到情况
        return -1;
    }
}
